﻿namespace QuickMail.View.Windows
{
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.IO;
    using System.Windows.Forms;

    using DbWorker.DataModels;

    using QuickMail.View.Controls;
    using QuickMail.DataModels;
    using QuickMail.BusinessLogic;
    using QuickMail.ViewModels;

    /// <summary>
    /// The properties window of the rule.
    /// </summary>
    public partial class PropertyWindow
    {
        #region Fields

        private readonly SendControl _sendControl = new SendControl();
        private readonly ReceiveControl _getControl = new ReceiveControl();
        public RuleVm CurrentRuleVm;

        #endregion //End Fields

        public PropertyWindow()
        {
            InitializeComponent();
            SetCurrentTranslate();

            ActionComboBox.SelectedIndex = 0;
            BrowseButton.Focus();

            AddChildrensCheckBox.Visibility = Visibility.Visible;
        }

        public PropertyWindow(RuleVm ruleVm)
        {
            InitializeComponent();
            SetCurrentTranslate();
            
            ActionComboBox.SelectedIndex = 0;
            BrowseButton.Focus();
            Load(ruleVm);
        }

        /// <summary>
        /// Sets the current translation for form elements.
        /// </summary>
        private void SetCurrentTranslate()
        {
            // ReSharper disable once RedundantThisQualifier
            this.Title = StaticFields.Lang.PropertyWindow.Title;
            PathTextBlock.Text = StaticFields.Lang.PropertyWindow.Path;
            BrowseButton.Content = StaticFields.Lang.PropertyWindow.Browse;
            RuleNameTextBlock.Text = StaticFields.Lang.PropertyWindow.RuleName;
            ActionTextBlock.Text = StaticFields.Lang.PropertyWindow.Action;
            NoneItem.Content = StaticFields.Lang.PropertyWindow.NoneAction;
            SendItem.Content = StaticFields.Lang.PropertyWindow.SendAction;
            ReceiveItem.Content = StaticFields.Lang.PropertyWindow.ReceiveAction;
            AddChildrensCheckBox.Content = StaticFields.Lang.PropertyWindow.AddChildrens;
            ApplyButton.Content = StaticFields.Lang.PropertyWindow.Apply;
            CancelButton.Content = StaticFields.Lang.PropertyWindow.Cancel;
        }

        /// <summary>
        /// Load form fields
        /// </summary>
        /// <param name="ruleVm">The selected rule.</param>
        private void Load(RuleVm ruleVm)
        {
            if (ruleVm == null)
                return;

            CurrentRuleVm = ruleVm;
            PathTextBox.Text = ruleVm.DirectoryPath;
            TitleTextBox.Text = ruleVm.Title;
            ActionComboBox.SelectedIndex = (int)ruleVm.Action;

            switch (ruleVm.Action)
            {
                case RuleAction.Send:
                    _sendControl.MailToTextBox.Text = ruleVm.Addresses;
                    _sendControl.SubjectTextBox.Text = ruleVm.Subject;
                    _sendControl.FilesTypesTextBox.Text = ruleVm.FilesTypes;
                    //_sendControl.MessageFromFileCheckBox.IsChecked = folder.MessageFromFile;
                    _sendControl.MessageTextBox.Text = ruleVm.MessageText;
                    break;
                case RuleAction.Receive:
                    _getControl.MailFromTextBox.Text = ruleVm.Addresses;
                    _getControl.ReplacementComboBox.SelectedIndex = (int)ruleVm.Replace;
                    _getControl.FilesTypesTextBox.Text = ruleVm.FilesTypes;
                    _getControl.SaveMessageCheckBox.IsChecked = ruleVm.SaveMessage;
                    break;
            }
        }
        
        /// <summary>
        /// Save form fields to the rule.
        /// </summary>
        private void Save()
        {
            if (CurrentRuleVm == null) 
                CurrentRuleVm = new RuleVm();

            CurrentRuleVm.Title = TitleTextBox.Text.Trim();
            CurrentRuleVm.DirectoryPath = PathTextBox.Text.Trim();
            CurrentRuleVm.Action = (RuleAction)ActionComboBox.SelectedIndex;

            if (Equals(ActionPresenter.Content, _sendControl))
            {
                CurrentRuleVm.Subject = _sendControl.SubjectTextBox.Text.Trim();
                CurrentRuleVm.Addresses = _sendControl.MailToTextBox.Text.Trim();
                CurrentRuleVm.AddressList = HelpWorker.DivideWords(_sendControl.MailToTextBox.Text.Trim());
                CurrentRuleVm.FilesTypes = _sendControl.FilesTypesTextBox.Text.Trim();
                CurrentRuleVm.FilesTypeList = HelpWorker.DivideWords(_sendControl.FilesTypesTextBox.Text.Trim());
                //CurrentFolder.MessageFromFile = _sendControl.MessageFromFileCheckBox.IsChecked == true;
                CurrentRuleVm.MessageText = _sendControl.MessageTextBox.Text.Trim();
            }

            if (Equals(ActionPresenter.Content, _getControl))
            {
                CurrentRuleVm.Addresses = _getControl.MailFromTextBox.Text.Trim();
                CurrentRuleVm.AddressList = HelpWorker.DivideWords(_getControl.MailFromTextBox.Text.Trim());
                CurrentRuleVm.FilesTypes = _getControl.FilesTypesTextBox.Text.Trim();
                CurrentRuleVm.FilesTypeList = HelpWorker.DivideWords(_getControl.FilesTypesTextBox.Text.Trim());
                CurrentRuleVm.Replace = (ReplaceFile)_getControl.ReplacementComboBox.SelectedIndex;
                CurrentRuleVm.SaveMessage = _getControl.SaveMessageCheckBox.IsChecked == true;
            }
        }

        /// <summary>
        /// Checking the correct fields are filled.
        /// </summary>
        /// <returns>true - correctly, false - incorrectly</returns>
        private bool CheckingFields()
        {
            PathTextBox.Background = TitleTextBox.Background =
                _sendControl.MailToTextBox.Background = _sendControl.SubjectTextBox.Background =
                _getControl.MailFromTextBox.Background = StaticFields.NormalColorBrush;

            bool result = true;

            if (string.IsNullOrEmpty(PathTextBox.Text.Trim()) || !Directory.Exists(PathTextBox.Text.Trim()))
            {
                PathTextBox.Background = StaticFields.ErrorColorBrush;
                PathTextBox.Focus();
                result = false;
            }

            if (string.IsNullOrEmpty(TitleTextBox.Text.Trim()))
            {
                TitleTextBox.Background = StaticFields.ErrorColorBrush;
                TitleTextBox.Focus();
                result = false;
            }

            //Checks the fields for sending letters.
            if (Equals(ActionPresenter.Content, _sendControl))
            {
                if (string.IsNullOrEmpty(_sendControl.MailToTextBox.Text.Trim()))
                {
                    _sendControl.MailToTextBox.Background = StaticFields.ErrorColorBrush;
                    _sendControl.MailToTextBox.Focus();
                    result = false;
                }

                if (HelpWorker.DivideWords(_sendControl.MailToTextBox.Text.Trim()).Any(tempAddress => !HelpWorker.IsValidMail(tempAddress)))
                {
                    _sendControl.MailToTextBox.Background = StaticFields.ErrorColorBrush;
                    _sendControl.MailToTextBox.Focus();
                    result = false;
                }

                if (string.IsNullOrEmpty(_sendControl.SubjectTextBox.Text.Trim()))
                {
                    _sendControl.SubjectTextBox.Background = StaticFields.ErrorColorBrush;
                    _sendControl.SubjectTextBox.Focus();
                    result = false;
                }
            }

            //Checks the fields for receiving letters.
            if (Equals(ActionPresenter.Content, _getControl))
            {
                if (string.IsNullOrEmpty(_getControl.MailFromTextBox.Text.Trim()))
                {
                    _getControl.MailFromTextBox.Background = StaticFields.ErrorColorBrush;
                    _getControl.MailFromTextBox.Focus();
                    result = false;
                }

                if (HelpWorker.DivideWords(_getControl.MailFromTextBox.Text.Trim()).Any(tempAddress => !HelpWorker.IsValidMail(tempAddress)))
                {
                    _getControl.MailFromTextBox.Background = StaticFields.ErrorColorBrush;
                    _getControl.MailFromTextBox.Focus();
                    result = false;
                }
            }

            return result;
        }

        #region Interface events.

        /// <summary>
        /// Shows the browse dialog.
        /// </summary>
        private void BrowseFolder_OnClick(object sender, RoutedEventArgs e)
        {
            var fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PathTextBox.Text = fbd.SelectedPath;

                if (string.IsNullOrEmpty(TitleTextBox.Text.Trim()))
                    TitleTextBox.Text = Path.GetFileName(fbd.SelectedPath);

                TitleTextBox.Focus();
            }
        }

        /// <summary>
        /// Change the selected action.
        /// </summary>
        private void ActionComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (ActionComboBox.SelectedIndex)
            {
                case 0:
                    ActionPresenter.Content = null;
                    break;
                case 1:
                    ActionPresenter.Content = _sendControl;
                    break;
                case 2:
                    ActionPresenter.Content = _getControl;
                    break;
            }

        }

        /// <summary>
        /// Apply click
        /// </summary>
        private void Apply_OnClick(object sender, RoutedEventArgs e)
        {
            if (!CheckingFields())
                return;

            Save();
            DialogResult = true;
        }

        #endregion //End interface events.
    }
}
